package com.example.common;

import java.io.Serializable;
import java.util.HashMap;

/**
 * 统一返回响应结果
 *
 * @author Ng
 */
public class Result<T> implements Serializable {

    public static final Integer ERROR = 400;
    public static final Integer SUCCESS = 200;

    private T data;          // 数据
    private Integer code;    // 编码 200:成功 400:失败
    private String message;  // 错误信息

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public int getCode() {
        return code;
    }

    public void setCode(Integer code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public static <T> Result<T> success() {
        return result(SUCCESS, "响应成功！", null);
    }

    public static <T> Result<T> success(T data) {
        return result(SUCCESS, "响应成功！", data);
    }

    public static <T> Result<T> success(String message, T data) {
        return result(SUCCESS, message, data);
    }

    public static <T> Result<T> error() {
        return result(ERROR, "响应失败！", null);
    }

    public static <T> Result<T> error(String message) {
        return result(ERROR, message, null);
    }

    public static <T> Result<T> error(T data) {
        return result(ERROR, "响应失败！", data);
    }

    public static <T> Result<T> error(String message, T data) {
        return result(ERROR, message, data);
    }

    public static <T> Result<T> error(Integer code, String message) {
        return result(code, message, null);
    }

    private static <T> Result<T> result(Integer code, String message, T data) {

        Result<T> result = new Result<>();
        result.setCode(code);
        result.setMessage(message);
        result.setData(data != null ? data : (T) new HashMap<>());
        return result;
    }
}
